import yagmail
from SelfStudy.FrameWork.ApiIhrmpytest.common.logger_util import get_logger
import zipfile
import os
from SelfStudy.FrameWork.ApiIhrmpytest.config import BASE_DIR

log = get_logger()


class EmailServe:

    @staticmethod
    def zip_report(file_path: str, out_path: str):
        """
        压缩指定文件夹到 out_path 路径的 zip 文件
        :param file_path: 目标文件夹路径
        :param out_path: 压缩文件完整保存路径（带 .zip）
        """
        zip_dir = os.path.dirname(out_path)
        os.makedirs(zip_dir, exist_ok=True)

        with zipfile.ZipFile(out_path, "w", zipfile.ZIP_DEFLATED) as zipf:
            for path, dirnames, filenames in os.walk(file_path):
                fpath = path.replace(file_path, '')  # 去掉根路径
                for filename in filenames:
                    zipf.write(
                        os.path.join(path, filename),
                        os.path.join(fpath, filename)
                    )

    @staticmethod
    def send_email(setting: dict, file_path: str, result_data_test: str):
        """
        发送带压缩报告的邮件
        :param setting: 邮件配置字典
        :param file_path: 需要压缩的文件夹路径
        :param result_data_test: 邮件正文
        """
        log.info('开始将报告压缩为 zip 包...')
        EmailServe.zip_report(file_path=file_path, out_path=setting['enclosures'])
        log.info('压缩完成！')

        try:
            yag = yagmail.SMTP(setting['user'], setting['password'], setting['host'])

            log.info('开始发送邮件...')
            yag.send(
                to=setting['addressees'],
                subject=setting['title'],
                contents=result_data_test,
                attachments=setting['enclosures']
            )
            yag.close()
            log.info('邮件发送成功！')

            # 邮件发送成功后删除压缩文件
            if os.path.exists(setting['enclosures']):
                os.remove(setting['enclosures'])
                log.info(f"已删除压缩文件: {setting['enclosures']}")
        except Exception as e:
            log.error(f"邮件发送失败: {str(e)}")
            raise


if __name__ == '__main__':
    # 设置压缩后的 zip 保存路径
    zip_path = os.path.join(BASE_DIR, "report_zip", "report.zip")

    # 邮件设置
    setting = {
        'user': '18676219827@163.com',
        'password': 'ZMYncYzNnnqHskHV',  # 授权码
        'host': 'smtp.163.com',
        'addressees': ['2486049424@qq.com'],
        'title': '人力资源管理项目测试报告',
        'enclosures': zip_path  # 压缩包路径作为附件
    }

    # 需要压缩的报告目录
    report_dir = os.path.join(BASE_DIR, "report")
    result_data_test = '请查收附件中的测试报告'

    EmailServe.send_email(setting, report_dir, result_data_test)